<template>
	<fui-tabs :tabs="tabs" @change="changeTab" :short="false" selectedColor="#333" sliderBackground="#333" />
	<view v-if="currentTab === '待送达'">
		<view style="margin-top: 20px;" v-if="messages === '您还没有未送达的订单'">
			<fui-empty src="https://zjdemo.xuande.work:8889/photo/65cfff1d2fbe4ceeac42524d021f21ff.png" title="暂无订单记录">
				<fui-button text="返回首页" :size="28" width="336rpx" height="84rpx" radius="100rpx" background="#fff"
					:margin="['64rpx','0']" borderColor="#333" color="#333" @click="goIndex"></fui-button>
			</fui-empty>
		</view>
		<view v-else>
			<view class="container" v-for="(food,index) in foodOrder">
				<view class="order-box">
					<view class="header">
						<view class="store-name">订单编号：{{food.orderId}}</view>
						<view class="status">{{orderType}}</view>
					</view>
					<view class="item" v-for="(items,itemsIndex) in food.cao" @click="godetailsOrder(food,items)">
						<image class="item-image" :src="items.comboImg"></image>
						<view class="item-details">
							<view class="item-title">{{items.comboName}}</view>
							<view class="item-options-quantity">
								<view class="item-options">{{items.comboContain}}</view>
								<view class="item-quantity">x{{nums[index][itemsIndex]}}</view>
							</view>
						</view>
					</view>

					<view class="footer">
						<view class="timestamp">{{food.createTime}}</view>
						<view class="total">共{{totalNums[index]}}件商品 合计: ¥{{food.money}}</view>
					</view>
					<view class="button-container">
						<button class="reorder-button" @click="godetailsOrder(food,items)">查看详情</button>
					</view>
				</view>
			</view>
		</view>


	</view>
	<view v-else-if="currentTab === '已送达'">
		<view style="margin-top: 20px;" v-if="message === '您还没有已送达的订单'">
			<fui-empty src="https://zjdemo.xuande.work:8889/photo/65cfff1d2fbe4ceeac42524d021f21ff.png" title="暂无订单记录">
				<fui-button text="返回首页" :size="28" width="336rpx" height="84rpx" radius="100rpx" background="#fff"
					:margin="['64rpx','0']" borderColor="#333" color="#333" @click="goIndex"></fui-button>
			</fui-empty>
		</view>
		<view v-else>
			<view class="container" v-for="(food,index) in foodOrders">
				<view class="order-box">
					<view class="header">
						<view class="store-name">订单编号：{{food.orderId}}</view>
						<view class="status">{{orderType}}</view>
					</view>
					<view class="item" v-for="(items,itemsIndex) in food.cao" @click="godetailsOrders(food,items)">
						<image class="item-image" :src="items.comboImg"></image>
						<view class="item-details">
							<view class="item-title">{{items.comboName}}</view>
							<view class="item-options-quantity">
								<view class="item-options">{{items.comboContain}}</view>
								<view class="item-quantity">x{{numss[index][itemsIndex]}}</view>
							</view>
						</view>
					</view>

					<view class="footer">
						<view class="timestamp">{{food.createTime}}</view>
						<view class="total">共{{totalNumss[index]}}件商品 合计: ¥{{food.money}}</view>
					</view>
					<view class="button-container">
						<button class="reorder-button">已送达</button>
					</view>
				</view>
			</view>
		</view>
	</view>

</template>
<script setup>
	import {
		url
	} from '@/utils/request.js';
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app';
	import {
		onPullDownRefresh,
		onReachBottom
	} from "@dcloudio/uni-app";

	const gozailaiyidan = () => {
		uni.switchTab({
			url: '../order/order'
		})
	}
	let orderStatusCache = {};



	// const  pollOrderStatus=()=> {
	//   uni.getStorage({
	//     key: 'openId',
	//     success(res) {
	//       const openId = res.data;
	//       uni.request({
	//         url: url + '/placeAnOrder/userSelectUnGetOrder', // 替换为你的后端接口
	//         method: 'GET',
	//         data: {
	//           openId: openId
	//         },
	//         success: (res) => {
	//           // 获取订单列表
	//           const orders = res.data.data;
	
	//           orders.forEach(order => {
	//             const orderId = order.orderId;
	//             const status = order.isGet; // 使用 isGet 字段判断订单是否送达（或退款）
	//             const riderRemark = order.riderRemark; // 骑手备注
	
	//             // 获取当前缓存的订单状态
	//             const cachedStatus = orderStatusCache[orderId];
	
	//             // 如果当前状态和缓存状态不一致，更新缓存并执行相应操作
	//             if (status !== cachedStatus) {
	//               // 如果订单状态是 "已退款" 且之前的状态不是 "已退款"，提示用户
	//               if (riderRemark && riderRemark.includes('退款') && status === '未送达') {
	//                 uni.showToast({
	//                   title: `订单 ${orderId} 已退款`,
	//                   icon: 'success'
	//                 });
	
	//                 // 更新缓存状态为 "已退款"
	//                 orderStatusCache[orderId] = '已退款';
	//               }
	//               // 如果订单状态是 "未接单"，也更新缓存
	//               else if (status === '未接单') {
	//                 orderStatusCache[orderId] = '未接单';
	//               }
	
	//               // 将更新后的缓存保存到本地存储
	//               uni.setStorage({
	//                 key: 'orderStatusCache',
	//                 data: orderStatusCache
	//               });
	//             }
	//           });
	//         },
	//         fail: (error) => {
	//           console.error('订单状态查询失败', error);
	//         }
	//       });
	//     },
	//     fail(err) {
	//       console.error('获取 openId 失败:', err);
	//     }
	//   });
	// }

	const nums = ref([]);
	const foodOrder = ref([]);
	const foodOrders = ref([]);
	const messages = ref(null)
	const totalNums = ref([]);
	const totalNumss = ref([]);

	const numss = ref([]);

	const message = ref(null)
	const fetchData = () => {
		uni.getStorage({
			key: 'openId',
			success: function(res) {
				uni.request({
					url: url + '/placeAnOrder/userSelectMyNoGetOrder',
					method: 'GET',
					data: {
						openId: res.data
					},
					success: (res) => {
						messages.value = res.data.message
						if (res.data && res.data.data) {

							console.log(messages)
							foodOrder.value = res.data.data;
							let allNums = [];
							let allTotalNums = [];

							res.data.data.forEach(order => {
								let numArray = order.num.split(',').map(Number);
								allNums.push(numArray);
								let total = numArray.reduce((a, b) => a + b, 0);
								allTotalNums.push(total);
							});
							nums.value = allNums;
							totalNums.value = allTotalNums;
							console.log(foodOrder.value);
							console.log("Nums array:", nums.value);
							console.log("Total nums array:", totalNums.value);
						} else {
							console.log("No data found for userSelectMyNoGetOrder");
						}
					}
				});

				uni.request({
					url: url + '/placeAnOrder/userSelectMyOKOrder',
					method: 'GET',
					data: {
						openId: res.data
					},
					success: (res) => {
						message.value = res.data.message
						console.log(message.value)
						if (res.data && res.data.data) {
							foodOrders.value = res.data.data;
							let allNumss = [];
							let allTotalNumss = [];

							res.data.data.forEach(order => {
								let numArrays = order.num.split(',').map(Number);
								allNumss.push(numArrays);
								let totals = numArrays.reduce((a, b) => a + b, 0);
								allTotalNumss.push(totals);
							});
							numss.value = allNumss;
							totalNumss.value = allTotalNumss;
							console.log(foodOrders.value);
							console.log("Nums array:", numss.value);
							console.log("Total nums array:", totalNumss.value);
						} else {
							console.log(res.data);
							console.log("No data found for userSelectMyOKOrder");
						}
					}
				});
			}
		});
	};

	onLoad((options) => {
		fetchData();
		uni.getStorage({
		  key: 'orderStatusCache',
		  success(res) {
		    orderStatusCache = res.data || {}; // 如果缓存存在，则赋值给 orderStatusCache
		  },
		  fail() {
		    console.log('未找到缓存，初始化为空缓存');
		    orderStatusCache = {}; // 如果没有缓存，则初始化为空对象
		  }
		});

		// setInterval(pollOrderStatus, 3000);
	});

	onPullDownRefresh(() => {
		console.log("下拉刷新");
		fetchData();
		setTimeout(() => {
			console.log('End pulldown refresh');
			uni.stopPullDownRefresh();
		}, 1000);
	});

	onReachBottom(() => {
		console.log("上拉加载更多");
		fetchData();
		setTimeout(() => {
			console.log('End reach bottom refresh');
		}, 1000);
	});

	const tabs = ref(['待送达', '已送达']);
	const currentTab = ref('待送达');

	const changeTab = (tab) => {
		currentTab.value = tabs.value[tab.index];
	};

	const goIndex = () => {
		uni.switchTab({
			url: '../index/index'
		});
	};

	const godetailsOrder = (food, items) => {
		const index = foodOrder.value.findIndex(order => order.orderId === food.orderId);
		if (index !== -1) {
			const orderDetails = {
				orderId: food.orderId,
				createTime: food.createTime,
				money: food.money,
				items: food.cao,
				nums: nums.value[index],
				totalNums: totalNums[index]
			};
			const orderDetailsStr = encodeURIComponent(JSON.stringify(orderDetails));
			uni.navigateTo({
				url: `/pages/detialsMyorder/detialsMyorder?orderDetails=${orderDetailsStr}`
			});
		}
	};
	const godetailsOrders = (food, items) => {
		const index = foodOrders.value.findIndex(order => order.orderId === food.orderId);
		if (index !== -1) {
			const orderDetails = {
				orderId: food.orderId,
				createTime: food.createTime,
				money: food.money,
				items: food.cao,
				nums: nums.value[index],
				totalNums: totalNums.value[index]
			};
			const orderDetailsStr = encodeURIComponent(JSON.stringify(orderDetails));
			uni.navigateTo({
				url: `/pages/detailsOrder/detailsOrder?orderDetails=${orderDetailsStr}`
			});
		}
	};
</script>


<style scoped>
	.container {
		padding: 10px;
	}

	.order-box {
		border: 1px solid #ddd;
		border-radius: 10px;
		padding: 10px;
		background-color: #fff;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
	}

	.status {
		color: #333;
		font-size: 14px;
	}

	.store-name {
		font-size: 14px;
		word-spacing: 10px;
	}

	.item {
		display: flex;
		border-bottom: 1px solid #f5f5f5;
		padding-bottom: 16px;
		margin-bottom: 16px;
	}

	.item-image {
		width: 36px;
		height: 36px;
		margin-right: 16px;
		align-self: center;
	}

	.item-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.item-title {
		font-size: 16px;
		/* font-weight: bold; */
	}

	.item-options-quantity {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 14px;
		color: #666;
		margin-bottom: 8px;
	}

	.item-quantity {
		color: #999;
	}

	.footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 10px;
	}

	.timestamp {
		font-size: 14px;
		color: #666;
	}

	.total {
		font-size: 16px;
		font-weight: bold;
	}

	.button-container {
		display: flex;
		justify-content: flex-end;
		margin-top: 10px;
	}

	.reorder-button {
		background-color: #333;
		color: #fff;
		border: none;
		padding: 5px 20px;
		margin-right: 0px;
		border-radius: 26px;
		font-size: 14px;
	}
</style>